package com.baoyouqun.controller.union;

import com.baoyouqun.entity.FileInfoLocal;
import com.baoyouqun.service.FilePreviewService;
import com.baoyouqun.service.IFileStorageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * 文件预览控制器
 */
@RestController
@RequestMapping("/api/files/preview")
@Tag(name = "文件预览接口", description = "提供文件在线预览功能")
@Slf4j
public class FilePreviewController {

    @Resource
    private FilePreviewService filePreviewService;

    @Resource
    private IFileStorageService fileStorageService;  // 新增依赖

    /**
     * 在线预览文件
     */
    @GetMapping("/{fileId}")
    @Operation(summary = "在线预览文件", description = "根据文件ID在线预览文件，支持图片、文本、PDF和Office文档")
    public void previewFile(
            @Parameter(description = "文件ID") @PathVariable String fileId,
            HttpServletResponse response) throws IOException {
        try {
            filePreviewService.previewFile(fileId, response);
        } catch (Exception e) {
            log.error("文件预览失败", e);
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write("文件预览失败：" + e.getMessage());
        }
    }

    /**
     * 获取图片缩略图
     */
    @GetMapping("/thumbnail/{fileId}")
    @Operation(summary = "获取图片缩略图", description = "根据文件ID获取图片缩略图")
    public void getThumbnail(
            @Parameter(description = "文件ID") @PathVariable String fileId,
            @Parameter(description = "缩略图宽度") @RequestParam(defaultValue = "200") int width,
            @Parameter(description = "缩略图高度") @RequestParam(defaultValue = "200") int height,
            HttpServletResponse response) throws IOException {
        try {
            // 修复参数传递：先获取文件信息再传递
            Long id;
            try {
                id = Long.parseLong(fileId);
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("文件ID格式错误");
            }
            FileInfoLocal fileInfo = fileStorageService.getFileInfoLocal(id);
            if (fileInfo == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            filePreviewService.generateThumbnail(fileInfo, width, height, response);
        } catch (Exception e) {
            log.error("生成缩略图失败", e);
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }
}